<template>
  <div id="configureTagAddEdit">
    <el-dialog
      class="about-set"
      :title="isAdd ? `添加【标签分类名称】` : '编辑分类'"
      :visible.sync="dialogData.isShow"
      width="420px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="labelCategoryName">
            <el-input
              clearable
              :maxlength="nameLength"
              show-word-limit
              v-model.trim="ruleForm.labelCategoryName"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类属性" prop="labelCategoryProperty">
            <el-select
              :disabled="isPrope"
              v-model="ruleForm.labelCategoryProperty"
              placeholder=""
            >
              <el-option
                v-for="item in labelPropeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="!this.isAdd" label="分类状态" prop="enabled">
            <el-select
              @change="enalChang()"
              v-model="ruleForm.enabled"
              placeholder=""
            >
              <el-option
                v-for="item in labelStatusList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              clearable
              placeholder="15个字符"
              maxlength="15"
              show-word-limit
              v-model.trim="ruleForm.remark"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEditLable,
  postAddLable,
  putEditLable,
  getLabelCategoryName
} from '@/api/contentTags/configureTag' // 接口
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { validateSpecial } from '@utils/validate'
export default {
  name: 'DialogAddEdit',
  msg: '配置标签分类-新增/编辑弹窗',
  props: ['dialogData', 'nameLength'],
  data() {
    var category = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择分类属性'))
      } else {
        callback()
        if (this.ruleForm.labelCategoryName) {
          this.$refs.ruleForm.validateField('labelCategoryName')
        }
      }
    }
    var valiLableNmae = (rule, value, callback) => {
      /*if (!validateSpecial(value)) {
        callback(new Error('请正确填写分类名称'))
      }*/
      // 校验标签分类名称是否重复
      let id = this.id ? this.id : 0
      let obj = {
        name: this.ruleForm.labelCategoryName,
        categoryLabelProperty: this.ruleForm.labelCategoryProperty,
        id: id
      }
      getLabelCategoryName(
        obj,
        (response) => {
          if (response) {
            //true已重复
            callback(new Error('分类名称已使用，请更换'))
          } else {
            //false-无重复
            callback()
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      isAdd: true, // 新增-true,编辑-false
      showTitle: '',
      loading: false,
      isPrope: false,
      statusList: [], // 字典状态
      id: null, // 字典id
      ruleForm: {
        labelCategoryName: '', // 分类名称
        labelCategoryProperty: '', // 分类属性
        enabled: '', // 分类状态
        remark: '' //备注
      },
      // 标签属性
      labelPropeList: [],
      // 标签属性
      labelStatusList: [],
      rules: {
        labelCategoryName: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { validator: valiLableNmae, trigger: 'blur' }
        ],
        labelCategoryProperty: [
          { required: true, message: '分类属性不能为空', trigger: 'blur' },
          {
            validator: category,
            trigger: 'change'
          }
        ],
        remark: {}
      }
    }
  },

  mounted() {
    this.isAdd = this.dialogData.id ? false : true
    if (!this.isAdd) {
      this.tagCount = this.dialogData.params
      if (this.tagCount) {
        this.isPrope = true
      }
      // 编辑
      this.id = this.dialogData.id
      this.getFormData()
    }
    this.getStatusList()
  },
  methods: {
    async getStatusList() {
      this.labelPropeList = await sysNormalDisable('sys_labels_attribute')
      this.labelStatusList = await sysNormalDisable('sys_labels_statu')
      //设置默认数据
      this.setDefaultValue()
    },
    /*设置默认数据*/
    setDefaultValue() {
      this.ruleForm.labelCategoryProperty = this.labelPropeList[0].dictValue
      this.ruleForm.enabled = this.labelStatusList[0].dictValue
    },
    /* 编辑时获取表单详情 */
    getFormData() {
      getEditLable(this.id, (response) => {
        this.ruleForm = { ...response }
        this.ruleForm.enabled = this.ruleForm.enabled.toString()
      })
    },
    // 状态切换提示
    enalChang() {
      if (this.ruleForm.enabled === 'false') {
        this.$confirm(
          '分类状态停用后，下面包含标签将随之停用,确定停用分类吗？',
          '系统提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(() => {
          this.ruleForm.enabled = 'true'
        })
      } else {
        return 'falase'
      }
    },
    /* 确认提交 */
    confirmLabel(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.subForm()
        } else {
          return false
        }
      })
    },
    /* 提交表单 */
    async subForm() {
      this.loading = true

      let obj = { ...this.ruleForm }
      obj.enabled = eval(this.ruleForm.enabled)
      if (this.isAdd) {
        // 新增
        await postAddLable(
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message.warning({
              message: response.message,
              type: 'warning'
            })
          }
        )
      } else {
        // 编辑
        putEditLable(
          this.id,
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message.warning({
              message: response.message,
              type: 'warning'
            })
          }
        )
      }
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.id = null
      this.dialogData.labelCategory = ''
      this.dialogData.isShow = false
    }
  }
}
</script>

<style lang="less">
#configureTagAddEdit {
  .el-input--suffix .el-input__inner {
    padding-right: 70px;
  }
}
</style>
